//
//  UnreadListView.swift
//  maozzi-rss
//
//  Created by 帽子 on 2020/5/22.
//  Copyright © 2020 帽子. All rights reserved.
//	未读列表 view

import SwiftUI
import UIKit

struct UnreadListView: View {
    @EnvironmentObject private var userData: UserData
    @State private var isPresented = false
    @State private var isAlert = false

    var body: some View {
        VStack {
            if self.userData.newsData.isEmpty {
                Image(systemName: "scribble")
                    .resizable()
                    .frame(width: 50, height: 50, alignment: .center)
                    .offset(x: 0, y: -100)

            } else {
                List(self.userData.newsData) { newsItem in
                    Button(action: {
                        self.isPresented.toggle()
                    }) {
                        NewsRowView(newsItem: newsItem).environmentObject(self.userData)
                    }.sheet(isPresented: self.$isPresented) {
                        NewsDetailView(newsItem: newsItem).environmentObject(self.userData)
                    }
                }.navigationBarTitle(Text("未读消息"), displayMode: .inline)
                    .navigationBarItems(trailing: Button(action: {
                        self.isAlert.toggle()
                    }) {
                        Text("全部已读")
                    }.alert(isPresented: self.$isAlert) {
                        // 删除确认
                        Alert(title: Text("确认删除？"), primaryButton: .destructive(Text("朕已阅！"), action: {
                            let arr: [NewsItem] = LocalCacheUtil.getAll(filename: UserData.readCacheFileName) + self.userData.newsData
                            let b = LocalCacheUtil.save(filename: UserData.readCacheFileName, value: Set(arr))
                            if b {
                                // 成功则清空 newsData
                                self.userData.newsData = []
                            }
                        }), secondaryButton: .cancel(Text("取消")))
                    })
            }
        }
    }
}

struct NewsListView_Previews: PreviewProvider {
    static var previews: some View {
        UnreadListView().environmentObject(UserData())
    }
}
